package com.jjh.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;


//@Component
//@PropertySource("classpath:application.yml")
public class JwtUtil {

    //@Value("${jwt.claim}")
    private final String claim = "username";

    //@Value("${jwt.signature}")
    private final String signature ="afafadfadfasdfafjawoepfjiwaefjekfjaklfjaslkfjf";

    //过期时间为30分钟
    private final Integer expirationMinutes = 100;

    /**
     * 生成token
     * @param userId  用户id
     * @param username 用户名
     * @return  token
     */
    public  String createToken(Integer userId,String username){
       return Jwts.builder()
               .setExpiration(new Date(System.currentTimeMillis() + expirationMinutes*60*1000))
               .claim(claim,username)
               .setSubject(String.valueOf(userId))
               .signWith(SignatureAlgorithm.HS256,signature)
               .compact();

    }

    /**
     * 解析token
     * @param token token
     * @return  用户id
     */
    public  String parseToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(signature)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 刷新token有效期
     * @param token 更新之后的token
     * @return 更新后的token
     */
    public String refreshToken(String token){
        String newToken;
        try{
            final Claims claims =Jwts.parser().setSigningKey(signature).parseClaimsJws(token).getBody();
            newToken = Jwts.builder()
                    .setClaims(claims)
                    .setExpiration(new Date(System.currentTimeMillis() + expirationMinutes*60*1000))
                    .signWith(SignatureAlgorithm.HS256,signature)
                    .compact();
        }catch (Exception e){
           newToken = null;
        }
        return newToken;
    }

    /**
     * 判断token是否过期
     * @param token token
     * @return 是否过期，true为过期，false为没过期
     */
    public  boolean isExpiration(String token){
        try {
            Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
            return false;
        } catch (Exception ex) {
            return true;
        }
    }


    /**
     * 获取token的过期时间
     * @param token token
     * @return 过期时间
     */
    public Date getExpirationDate(String token) {
        Claims claims = Jwts.parser().setSigningKey(signature).parseClaimsJws(token).getBody();
        return claims.getExpiration();
    }



}
